/*
 * 关卡编辑
 */
import * as React from 'react';
import { connect } from 'react-redux';
import { get } from 'lodash';
import { createLevel, updateLevel } from 'actions/level';
import CustomModal from 'components/common/CustomModal';

import { Input, Button, message, Form } from 'antd';

import { isLoading } from 'utils/utils';
import ACTIONS from 'constants/level';

interface LevelEditProps {
  dispatch: (action: any) => any;
  onOk: () => any;
  onCancel: () => any;
  form: any;
  level: number;
  lessonId: number;
  loadingGroup: any;
  editLevel: any;
}

class Edit extends React.Component<LevelEditProps> {
  loadingKey: string;
  static defaultProps: LevelEditProps = {
    dispatch: () => {},
    onOk: () => {},
    onCancel: () => {},
    form: {},
    lessonId: 0,
    level: 1,
    loadingGroup: {},
    editLevel: 0,
  };
  constructor(props: LevelEditProps) {
    super(props);

    this.loadingKey = props.editLevel ? ACTIONS.UPDATE : ACTIONS.CREATE;
  }

  componentDidMount() {
    this.initFormValue();
  }

  initFormValue() {
    const { form, editLevel } = this.props;
    const description = get(editLevel, 'description', '');
    form.setFieldsValue({
      description,
    });
  }

  componentWillReceiveProps(nextProps: any) {
    const { lessonId } = nextProps;
    const { lessonId: oldLessonId } = this.props;

    if (lessonId !== oldLessonId) {
      this.initFormValue();
    }
  }

  handleSubmit = (e: any) => {
    e.preventDefault();

    const { form, dispatch, loadingGroup, lessonId, onOk, editLevel, level } = this.props;

    if (!isLoading(loadingGroup, this.loadingKey)) {
      form.validateFields((error: any, values: any) => {
        if (error) return;

        let data: any = {};
        Object.keys(values).map((key: any) => {
          const val = values[key];
          if (val) {
            data[key] = val;
          }
        });

        data = { ...data, level };

        const action = editLevel
          ? updateLevel(lessonId, editLevel.id, data)
          : createLevel(lessonId, data);

        dispatch(action).then((result: any) => {
          if (result.code) {
            message.error(result.msg);
          } else {
            message.success('保存成功');
            this.handleClose();

            onOk();
          }
        });
      });
    }
  };

  handleClose = () => {
    this.props.onCancel();
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { loadingGroup, editLevel, level } = this.props;
    const title = editLevel ? `编辑第${level}关` : `新增第${level}关`;

    return (
      <CustomModal title={title} footer={false} onCancel={this.handleClose} width={500}>
        <Form onSubmit={this.handleSubmit}>
          <Form.Item label="课程描述">
            {getFieldDecorator('description')(
              <Input.TextArea
                autosize={{
                  minRows: 2,
                  maxRows: 6,
                }}
              />
            )}
          </Form.Item>
          <Form.Item>
            <Button.Group>
              <Button
                type="primary"
                htmlType="submit"
                loading={isLoading(loadingGroup, this.loadingKey)}>
                &nbsp;&nbsp;&nbsp;提交&nbsp;&nbsp;&nbsp;
              </Button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              <Button onClick={this.handleClose}>取消</Button>
            </Button.Group>
          </Form.Item>
        </Form>
      </CustomModal>
    );
  }
}

// 父组件props传递的参数
interface OwnProps {
  level: number;
  lessonId: number;
  editLevel: any;
  onOk: () => any;
  onCancel: () => any;
}

function mapStateToProps(state: any, ownProps: OwnProps) {
  const { loadingGroup } = state;
  const { level, lessonId, editLevel, onOk, onCancel } = ownProps;

  return {
    loadingGroup,
    editLevel,
    level,
    lessonId,
    onOk,
    onCancel,
  };
}

export default connect(mapStateToProps)(Form.create()(Edit));
